<?php
/**
 * 编写者：Jayson
 * 编写日期：2024-06-13 09:25:29
 */

namespace App\Http\Controllers\applet;

use App\Http\Controllers\Controller;
use App\Jobs\NewsExample;
use App\Models\users\UsersModel;
use Illuminate\Support\Facades\Redis;
use lxs\aliyun\OssStorage;
use lxs\aliyun\SendSms;
use lxs\api\ApiResponse;
use lxs\tools\AuthToken;
use lxs\tools\Tools;

class LoginController extends Controller {

    /**
     * 获取微信头像
     */
    public function getUserAvatar() {
        $file = request()->file('file');
        $path = Request()->input('name');
        if ($path) {
            $path = 'tmui/' . $path;
        }
        if (!$file) {
            return ApiResponse::apiResponseData(101, "请上传头像");
        }
        $result = (new OssStorage())->Uploads($file, $path);
        if ($result) {
            return ApiResponse::apiResponseData(200, "上传成功", [
                'url' => $result,
            ]);
        }
        return ApiResponse::apiResponseData(102, "上传失败");
    }

    /**
     * 发送验证码
     */
    public function sendCaptcha() {
        $mobile = request()->input('mobile');

        if (!$mobile) {
            return ApiResponse::apiResponseData(101, "请输入手机号码");
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return ApiResponse::apiResponseData(102, "手机号码格式不正确");
        }

        // 生成随机验证码
        $captcha = mt_rand(100000, 999999);

        Redis::setEx($mobile, 300, $captcha);

        if (in_array($mobile, ['13710624516'])) {
            return ApiResponse::apiResponseData(200, '验证码发送成功' . $captcha, [
                'captcha' => $captcha,
            ]);
        }

        $sendSms = new SendSms();
        $result = $sendSms->send($mobile, ['code' => $captcha], 'login_code');
        if ($result !== true) {
            return ApiResponse::apiResponseData(103, "发送失败");
        }

        return ApiResponse::apiResponseData(200, "验证码发送成功");
    }


    /**
     * 用户注册
     */
    public function register() {
        $data = request()->all();

        if (!$data['mobile']) {
            return ApiResponse::apiResponseData(101, "请输入手机号码");
        }
        if (!$data['password']) {
            return ApiResponse::apiResponseData(102, "请输入密码");
        }
        if (!$data['nickname']) {
            return ApiResponse::apiResponseData(103, "请输入昵称");
        }
        if (!$data['captcha']) {
            return ApiResponse::apiResponseData(104, "请输入验证码");
        }
        if (!preg_match('/^1[3-9]\d{9}$/', $data['mobile'])) {
            return ApiResponse::apiResponseData(103, "手机号码格式不正确");
        }
        if (!preg_match('/^[a-zA-Z0-9]{6,20}$/', $data['password'])) {
            return ApiResponse::apiResponseData(104, "密码格式不正确");
        }
//        if (!preg_match('/^[a-zA-Z0-9]{6,20}$/', $data['nickname'])) {
//            return ApiResponse::apiResponseData(105, "昵称格式不正确");
//        }
        if (Redis::get($data['mobile']) != $data['captcha']) {
            return ApiResponse::apiResponseData(105, "验证码不正确");
        }

        $user_list = UsersModel::where('mobile', $data['mobile'])->first();
        if ($user_list) {
            NewsExample::dispatch($user_list->uid);
            return ApiResponse::apiResponseData(106, "该手机号码已注册");
        } else {
            $user_list = UsersModel::create([
                'nickname' => $data['nickname'],
                'mobile' => $data['mobile'],
                'password' => hash_hmac('sha256', $data['password'], config('app.key')),
                'avatar' => $data['avatar'] ?? '',
                'create_time' => time(),
            ]);
            if ($user_list){
                return ApiResponse::apiResponseData(200, "注册成功");
            }
            return ApiResponse::apiResponseData(107, "注册失败");
        }
    }


    /**
     * 密码登录提交
     */
    public function passwordLoginSubmit() {
        $mobile = request()->input('mobile');
        $password = request()->input('password');

        if (!$mobile) {
            return ApiResponse::apiResponseData(101, "请输入手机号码");
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return ApiResponse::apiResponseData(102, "手机号码格式不正确");
        }

        if (!$password) {
            return ApiResponse::apiResponseData(103, "请输入密码");
        }

        $user_list = UsersModel::where('mobile', $mobile)->first();
        if ($user_list) {
            $user_cancel_time = Tools::Config('user.CANCEL_TIME');
            $days = $user_cancel_time * 24 * 60 * 60;
            if ($user_list->is_cancel == 1 && time() > ($user_list->cancel_time + $days)) {
                return ApiResponse::apiResponseData(106, '该账号已注销');
            }
            if (hash_hmac('sha256', $password, config('app.key')) == $user_list->password) {
                NewsExample::dispatch($user_list->uid);
                $auth = new AuthToken();
                $token = $auth->createToken($user_list->id);
                return ApiResponse::apiResponseData(200, "登录成功", [
                    'token' => $token,
                ]);
            } else {
                return ApiResponse::apiResponseData(104, "密码不正确");
            }
        } else {
           return ApiResponse::apiResponseData(105, "用户不存在");
       }
    }


    /**
     * 用户登录
     */
    public function captchaLoginSubmit() {
        $mobile = request()->input('mobile');
        $captcha = request()->input('captcha');

        if (!$mobile) {
            return ApiResponse::apiResponseData(101, "请输入手机号码");
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return ApiResponse::apiResponseData(102, "手机号码格式不正确");
        }

        if (!$captcha) {
            return ApiResponse::apiResponseData(103, "请输入验证码");
        }

        $cacheCaptcha = Redis::get($mobile);

        if ($cacheCaptcha != $captcha) {
            return ApiResponse::apiResponseData(104, "验证码不正确");
        }

        // 判断用户是否存在
        $user_list = UsersModel::where('mobile', $mobile)->first();
        if (!$user_list) {
//            $res = [
//                'nickname' => $mobile,
//                'mobile' => $mobile,
//                'avatar' => 'https://guzhong1.oss-cn-shenzhen.aliyuncs.com/%E5%8D%A1%E5%88%B8%E5%B0%8F%E7%A8%8B%E5%BA%8F/%E4%B8%AA%E4%BA%BA%E4%B8%AD%E5%BF%83/%E5%A4%B4%E5%83%8F.jpg',
//                'add_time' => time(),
//            ];
//            $user_list = UsersModel::create($res);
            return ApiResponse::apiResponseData(105, "用户不存在");
        }

        $user_cancel_time = Tools::Config('user.CANCEL_TIME');
        $days = $user_cancel_time * 24 * 60 * 60;
        if ( $user_list->is_cancel == 1 && time() > ($user_list->cancel_time + $days) ) {
            return ApiResponse::apiResponseData(106, "该账号已注销");
        }

        NewsExample::dispatch($user_list->uid);
        $auth = new AuthToken();
        $token = $auth->createToken($user_list->id);

        return ApiResponse::apiResponseData(200, "登录成功", [
            'token' => $token,
        ]);
    }


    /**
     * 忘记密码
     */
    public function forgetPassword() {
        $mobile = request()->input('mobile');
        $password = request()->input('password');
        $captcha = request()->input('captcha');

        if (!$mobile) {
            return ApiResponse::apiResponseData(101, "请输入手机号码");
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return ApiResponse::apiResponseData(102, "手机号码格式不正确");
        }

        if (!$password) {
            return ApiResponse::apiResponseData(103, "请输入密码");
        }

        if (!$captcha) {
            return ApiResponse::apiResponseData(104, "请输入验证码");
        }

        if (Redis::get($mobile) != $captcha) {
            return ApiResponse::apiResponseData(105, "验证码不正确");
        }

        $user_list = UsersModel::where('mobile', $mobile)->first();
        if ($user_list) {
            $user_list->password = hash_hmac('sha256', $password, config('app.key'));
            $user_list->save();
            return ApiResponse::apiResponseData(200, "修改成功");
        } else {
            return ApiResponse::apiResponseData(106, "用户不存在");
        }
    }


    /**
     * 微信小程序退出登录
     */
    public function wechatLogout(): \Illuminate\Http\JsonResponse
    {
        $auth = new AuthToken();
        $auth->destroyToken();
        return ApiResponse::apiResponseData(100, '退出成功');
    }


}
